<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <title>WebSocket 聊天室</title>
  <style>
    body {
      font-family: sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      height: 100vh;
    }

    #chat {
      flex: 1;
      overflow-y: auto;
      padding: 10px;
      background: #f9f9f9;
    }

    #chat p {
      margin: 5px 0;
    }

    #input {
      display: flex;
      border-top: 1px solid #ccc;
    }

    #input input {
      flex: 1;
      padding: 10px;
      border: none;
    }

    #input button {
      padding: 10px;
      border: none;
      background: #333;
      color: white;
      cursor: pointer;
    }
  </style>
</head>

<body>

  <div id="chat"></div>
  <div id="input">
    <input type="text" id="msgInput" placeholder="输入消息..." />
    <button onclick="sendMessage()">发送</button>
  </div>

  <div>
    <input type="text" id="privateToUser" placeholder="私聊用户ID" />
    <input type="text" id="privateMsgInput" placeholder="私聊内容" />
    <button onclick="sendPrivateMessage()">发送私信</button>
  </div>

  <script>
    let nickname = '';
    while (!nickname) {
      nickname = prompt('请输入你的昵称：');
    }

    const socket = new WebSocket('ws://localhost:8080');
    const chat = document.getElementById('chat');

    // WebSocket 连接打开时注册用户
    socket.onopen = () => {
      socket.send(JSON.stringify({ type: 'register', userId: nickname }));
    };

    // 处理服务器发来的消息
    socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      const p = document.createElement('p');
      if (data.type === 'system') {
        p.innerHTML = `<strong>系统消息:</strong> ${data.message}`;
      } else if (data.type === 'broadcast') {
        p.innerHTML = `<strong>${data.from}</strong> [广播]: ${data.message}`;
      } else if (data.type === 'private') {
        p.innerHTML = `<strong>${data.from}</strong> [私信]: ${data.message}`;
      } else if (data.type === 'error') {
        p.innerHTML = `<strong>错误:</strong> ${data.message}`;
      }
      chat.appendChild(p);
      chat.scrollTop = chat.scrollHeight;
    };

    // 发送广播消息
    function sendMessage() {
      const message = document.getElementById('msgInput').value;
      if (message.trim()) {
        socket.send(JSON.stringify({ type: 'broadcast', message: message }));
        document.getElementById('msgInput').value = '';
      }
    }

    // 发送私信
    function sendPrivateMessage() {
      const toUser = document.getElementById('privateToUser').value;
      const privateMessage = document.getElementById('privateMsgInput').value;
      if (toUser.trim() && privateMessage.trim()) {
        socket.send(JSON.stringify({ type: 'private', to: toUser, message: privateMessage }));
        document.getElementById('privateToUser').value = '';
        document.getElementById('privateMsgInput').value = '';
      }
    }
  </script>
</body>

</html>